package com.huluobo.mvvmdemo2006a.repo;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.huluobo.mvvmdemo2006a.model.Bean;
import com.huluobo.mvvmdemo2006a.model.Product;
import com.huluobo.mvvmdemo2006a.request.Request;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by lc on 2023/1/6.
 * 首页商品的数据仓库,Repo负责网络请求,相当于M层
 * MutableLiveData 这是LiveData的数据源,可以通过Repo获取到实时的数据源,当他发生改变时,外部可以观测的到
 */
public class ShopRepo {
    //最终使用的数据源
    private MutableLiveData<List<Product>> mutableProductList;

    //对外暴露获取数据源的方法
    public LiveData<List<Product>> getProducts() {
        if (mutableProductList == null) {
            mutableProductList = new MutableLiveData<>();
            loadProducts();
        }
        return mutableProductList;
    }

    private void loadProducts() {
        List<Product> productList = new ArrayList<>();//创建需要给LiveData的集合
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Request.HOST)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Call<Bean> call = retrofit.create(Request.class).getBean();
        call.enqueue(new Callback<Bean>() {
            @Override
            public void onResponse(Call<Bean> call, Response<Bean> response) {
                //解析网络数据,并且将数据json转换为对象并添加到集合中
                for (int i = 0; i < response.body().data.size(); i++) {
                    Product product = new Product(
                            response.body().data.get(i).id,
                            response.body().data.get(i).title,
                            response.body().data.get(i).num,
                            true,
                            response.body().data.get(i).pic
                    );
                    productList.add(product);
                }
                //给LiveData设置数据
                mutableProductList.setValue(productList);
            }

            @Override
            public void onFailure(Call<Bean> call, Throwable t) {
                Log.i("TagA", "e:" + t.getMessage());
            }
        });
    }
}
